/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.interceptor.ApiAccessInterceptor.java
 * <p>
 * 类产生时间: 2014-6-4 0004 下午 12:42
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.interceptor;

import com.google.common.base.Strings;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 客户端API访问拦截器<br/>
 * 在此拦截器，需要处理请求客户端类型处理，访问频率、权限控制
 *
 * @author: chenw
 * @time: 2014-6-4 0004 下午 12:42
 */
public class ApiAccessInterceptor implements HandlerInterceptor {

    private final Logger client = Logger.getLogger("client");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("User-Agent");
        UserAgent agent = Strings.isNullOrEmpty(header) ? null : UserAgent.parseUserAgentString(header);
        request.setAttribute("USER_AGENT_OBJ", agent);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        return true;
        //判断是否为移动设备(包括手机和平板设备)
//        boolean isMobileDevice = agent.getOperatingSystem().isMobileDevice();
//        if (isMobileDevice) {
////            response.setHeader("Access-Control-Allow-Origin", "http://localhost");
//            return true;
//        } else {
//
//            PrintWriter writer = response.getWriter();
////            response.setHeader("Refer", "localhost");
//            response.setContentType("application/json; charset=UTF-8");
//            String msg = String.format("{\"succ\":false,\"code\":403,\"error\":\"\\u5f53\\u524d\\u5ba2\\u6237\\u7aef\\u8bbf\\u95ee\\u53d7\\u9650\",\"time\":%s}", System.currentTimeMillis());
//            writer.write(msg);
//            writer.flush();
//            writer.close();
//            return false;
//        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Headers", "GET");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserAgent agent = ((UserAgent) request.getAttribute("USER_AGENT_OBJ"));
        if (!Objects.isNull(agent)) {
            OperatingSystem os = agent.getOperatingSystem();
            String userId = request.getParameter("USER_ID");
            String userName = request.getParameter("USER_NAME");
            MDC.put("ip", request.getRemoteHost());
            MDC.put("os", agent.getOperatingSystem());
            MDC.put("os_n", agent.getOperatingSystem().getName());
            MDC.put("dt", agent.getOperatingSystem().getDeviceType());
            MDC.put("uid", null != userId ? userId : 0);
            MDC.put("un", null != userName ? userName : "");
            Browser browser = agent.getBrowser();
            if (null != browser) {
                //            MDC.put("url", request.getRequestURL());
                MDC.put("bv", null == agent.getBrowserVersion() ? "" : agent.getBrowserVersion());
                MDC.put("bn", agent.getBrowser().getName());
                MDC.put("bg", agent.getBrowser().getGroup());
                MDC.put("bt", agent.getBrowser().getBrowserType());
            } else {
                MDC.put("bv", "");
                MDC.put("bn", "");
                MDC.put("bg", "");
                MDC.put("bt", "");
            }
            MDC.put("mod", "abc");
//            client.info(request.getRequestURL());
        }


    }
}
